package com.keensense.vcm.internal;

import static com.keensense.vcm.common.parser.ResponseParsers.spatiotemporalResponseParser;
import static com.keensense.vcm.internal.VCMResourcePathConstants.SPATIOTEMPORAL_COLLISION;
import static com.keensense.vcm.internal.VCMResourcePathConstants.SPATIOTEMPORAL_FREQUENCY;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.MessageFormat;

import com.keensense.vcm.HttpMethod;
import com.keensense.vcm.common.auth.CredentialsProvider;
import com.keensense.vcm.common.comm.RequestMessage;
import com.keensense.vcm.common.comm.ServiceClient;
import com.keensense.vcm.model.SpatiotemporalRequest;
import com.keensense.vcm.model.SpatiotemporalResponse;

/**
 * 时空碰撞
 *
 * @author lanjian
 * @date 2020/5/22 10:10 上午
 */
public class SpatiotemporalOperation extends VCMOperation {

    public SpatiotemporalOperation(ServiceClient client, CredentialsProvider credsProvider) {
        super(client, credsProvider);
    }

    /**
     * 统计同时在2个时空下的出现的人员和人员次数
     *
     * @param spatiotemporalRequest
     * @return
     */
    public SpatiotemporalResponse collide(SpatiotemporalRequest spatiotemporalRequest) {
        String xml = getXmlFromObject(spatiotemporalRequest, SpatiotemporalRequest.class);
        InputStream in = new ByteArrayInputStream(xml.getBytes());
        RequestMessage request =
                new VCMRequestMessageBuilder(this.client).setInputStream(in).setMethod(HttpMethod.POST).build();
        request.setResourcePath(SPATIOTEMPORAL_COLLISION);
        return doOperation(request, spatiotemporalResponseParser, true);
    }

    /**
     * 统计同时在2个时空下的出现的人员和人员次数
     *
     * @param spatiotemporalRequest
     * @return
     */
    public SpatiotemporalResponse calcFrequency(SpatiotemporalRequest spatiotemporalRequest) {
        String xml = getXmlFromObject(spatiotemporalRequest, SpatiotemporalRequest.class);
        InputStream in = new ByteArrayInputStream(xml.getBytes());
        RequestMessage request =
                new VCMRequestMessageBuilder(this.client).setInputStream(in).setInputSize(xml.getBytes().length).setEndpoint(endpoint).setMethod(HttpMethod.POST).build();
        request.setResourcePath(SPATIOTEMPORAL_FREQUENCY);
        return doOperation(request, spatiotemporalResponseParser, true);
    }

    /**
     * 获取时空分析任务结果
     *
     * @param taskId
     * @return
     */
    public SpatiotemporalResponse getTaskResult(String taskId) {
        RequestMessage request = new VCMRequestMessageBuilder(this.client).setMethod(HttpMethod.GET).build();
        request.setResourcePath(MessageFormat.format(VCMResourcePathConstants.SPATIOTEMPORAL_TASK_STATUS, taskId));
        return doOperation(request, spatiotemporalResponseParser, true);
    }

}
